package cn.mj.common;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class InitApplication implements ApplicationListener<ContextRefreshedEvent>{

	
	private static final String ZK_NODES = "192.168.1.101:2181,192.168.1.102:2181,192.168.1.103:2181";
	
	private static final String PATH = "/p";
	
	private CuratorFramework curatorFramework = null;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		curatorFramework = CuratorFrameworkFactory.builder().connectString(ZK_NODES).retryPolicy(new ExponentialBackoffRetry(100, 2)).sessionTimeoutMs(1000).build();
		curatorFramework.start();
		PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, PATH, true);
		
//		设置成事件驱动型
		try {
			pathChildrenCache.start(StartMode.POST_INITIALIZED_EVENT);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//		当子节点的监听启动时，如果监听节点PATH不存在，就会自动创建监听节点PATH。特别注意，如果你后期把PATH节点删除了，此监听也就同时失效，你再创建PATH和子节点，此监听都不再会触发
		
		
		pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
			
			@Override
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				
//				break关键字可以结束switch语句，如果没有break，则从符合条件的case开始一直往下执行到switch结束或者遇到break。
				switch (event.getType()) {
					case CHILD_ADDED:
						System.out.println("                                  ");
						System.out.println("CHILD_ADDED==" + event.getData().getPath());
						System.out.println("CHILD_ADDED==" + new String(event.getData().getData()));
						break;
					case CHILD_UPDATED:
						System.out.println("                                  ");
						System.out.println("CHILD_UPDATED==" + event.getData().getPath());
						System.out.println("CHILD_UPDATED==" + new String(event.getData().getData()));
						break;
					case CHILD_REMOVED:
						System.out.println("                                  ");
						System.out.println("CHILD_REMOVED==" + event.getData().getPath());
						System.out.println("CHILD_REMOVED==" + new String(event.getData().getData()));
					break;

				default:
					break;
				}
				
			}
		});
		
		System.out.println("启动watcher成功。。。。");
	}

	
}
